package com.attendance.aspectj;

import com.attendance.annotation.Supplement;
import com.attendance.base.BaseEntity;
import com.attendance.spring.SpringAopUtils;
import com.attendance.spring.SpringSecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 基础实体方面
 *
 * @author 鵺丶
 * @date 2021/03/12
 */
@Aspect
@Component
public class BaseEntityAspect {

    @Pointcut("@annotation(com.attendance.annotation.Supplement)")
    public void annotationPointCut() { }

    @Before("annotationPointCut()")
    public void doBeforeReturning(JoinPoint joinPoint) {
        Supplement annotation = SpringAopUtils.getAnnotation(joinPoint, Supplement.class);
        for (Object obj : joinPoint.getArgs()) {
            if (obj instanceof BaseEntity) {
                if (annotation != null) {
                    switch (annotation.type()) {
                        case UPDATE:
                            ((BaseEntity) obj).setUpdateBy(SpringSecurityUtils.getUserName());
                            ((BaseEntity) obj).setUpdateTime(new Date());
                            break;
                        case PUT:
                            ((BaseEntity) obj).setCreateBy(SpringSecurityUtils.getUserName());
                            ((BaseEntity) obj).setCreateTime(new Date());
                            break;
                        default:
                            throw new IllegalStateException("Unexpected value: " + annotation.type());
                    }
                }
            }
        }
    }

}
